#include "log.hpp"
#include "inetaddr.hpp"
#include "common.hpp"
using namespace hllog;
using namespace hladdr;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "usage : " << argv[0] << " server_ip server_port" << std::endl;
        exit(1);
    }
    InetAddr server(argv[1], std::stoi(argv[2]));
    // 1. socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(Level::FATAL) << "socket error";
        exit(SOCKET_ERR);
    }
    LOG(Level::INFO) << "socket success, sockfd : " << sockfd;

    // 2. connect
    int n = connect(sockfd, server.GetInetAddr(), server.GetLen());
    if (n < 0)
    {
        LOG(Level::FATAL) << "connect error";
        exit(CONNECT_ERR);
    }
    LOG(Level::INFO) << "connect success, sockfd : " << sockfd;

    // 写/读
    while (true)
    {
        std::string massage;
        std::cout << "Please Enter #";
        std::getline(std::cin, massage);
        int wn = write(sockfd, massage.c_str(), massage.size());
        if (wn < 0)
        {
            LOG(Level::WARNING) << "write error";
            continue;
        }
        // 接受
        char buff[256];
        int rn = read(sockfd, buff, sizeof(buff) - 1);
        if (rn < 0)
            continue;
        else if (rn == 0)
            break;
        buff[rn] = '\0';
        std::cout << "recive : " << buff << std::endl;
    }
    return 0;
}